<!-- indexBar -->

<style lang="scss" scoped></style>

<template>
<!-- 搜索框 -->
<div class=" flex items-center w-full h-[48px] p-[4px] bg-white shadow-sm mb-[16px]">
  <input v-model="nameText" placeholder="请输入搜索的内容" class="flex-1 h-full rounded-md pl-[14px] text-[14px]" />
  <div class="w-[80px] text-[14px] text-center bg-blue-400 h-full leading-[40px]">搜索</div>
</div> 
<div class="relative h-full overflow-y-auto" @scroll="onScroll">
  <!-- 列表 -->
  <div v-for="item in listData.sortedGroupedArray" :key="item.indexes" class="px-[16px]">
    <div
      class="text-[12px] text-#666666 link_title"
      :id="`${item.indexes}`"
    >{{ item.indexes }}</div>
    <div v-for="cItem in item[item.indexes]" :key="cItem.userId" class="flex items-center mb-[16px]" >
      <div class="w-[40px] h-[40px] rounded-[50%] mr-[16px]">
        <img :src="cItem.avatar" alt="" class="w-full h-full rounded-[50%]" >
      </div>
      <div class="text-#333333 text-[14px] font-semibold">{{ cItem.nickname }}</div>
    </div>
  </div>
  <!-- 字母索引 -->
  <div class="fixed right-0 top-[50%] translate-y-[-50%] py-[16px] flex flex-col">
    <a
      v-for="(item, index) in listData.groupedKeys"
      :key="item" class="text-[12px] text-#333333 px-[16px]"
      :class="{ 'text-blue-400': activeAnchor === index }"
      :href="`#${item}`"
      @click="onJump(index)"
    >
      {{ item }}
  </a>
  </div> 
</div>
</template>

<script setup>
import { computed, ref } from 'vue';
import { userList, sortedNames, onScrollEvent } from './data-options'
// 需求，根据获取到的数据中，name 的首字母，排序成 A_Z，如果不是字母就用 # 代替

const nameText = ref('')

const activeAnchor = ref(0)

const listData = computed(() => {
  if (nameText.value) {
    const data = userList.filter(item => item.nickname.toLowerCase().includes(nameText.value.toLowerCase()))
    const { sortedGroupedArray = [] } = sortedNames(data, 'nickname')
    if (!sortedGroupedArray[0]) {
      return {
        groupedKeys: [],
        sortedGroupedArray: []
      }
    }
    return {
      sortedGroupedArray,
      groupedKeys: []
    }
  }
  const { sortedGroupedArray, groupedKeys } = sortedNames(userList, 'nickname')
  return {
    sortedGroupedArray,
    groupedKeys
  }
})

// 滚动页面
const onScroll = (e) => {
  activeAnchor.value = onScrollEvent(e, listData.value.groupedKeys, '.link_title')
}

// 点击索引
const onJump = index => {
  activeAnchor.value = index
}


</script>